package com.uplift.mgt.qa.service.impl;

import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.github.pagehelper.PageHelper;
import com.uplift.common.utils.UUIDGenerater;
import com.uplift.mgt.qa.dao.IQaMapper;
import com.uplift.mgt.qa.model.Qa;
import com.uplift.mgt.qa.service.IQaService;

@Service
@Transactional
public class QaServiceImpl implements IQaService {

	@Autowired
	private IQaMapper QaMapper;

	@Override
	public List<Map<String, Object>> queryQa(Qa qa) {
		PageHelper.startPage(qa.getPage(), qa.getLimit());
		
		List<Map<String, Object>> list = this.QaMapper.selectQa(qa);
		for (Map<String, Object> map : list) {
			String relation = MapUtils.getString(map, "relation");
			String answer = MapUtils.getString(map, "answer");
			if (StringUtils.equals("2", relation)) {
				String[] ids = StringUtils.split(answer, ",");
				Qa childParam = new Qa();
				childParam.setIdsList(Arrays.asList(ids));
				List<Map<String, Object>> childList = this.QaMapper.selectQa(childParam);
				map.put("cqs", childList);
				map.remove("answer");
			}
		}

		return list;
	}

	@Override
	public int saveQa(Qa qa) {
		qa.setId(UUIDGenerater.generate());
		qa.setCreateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
		return this.QaMapper.insertQa(qa);
	}

	@Override
	public int removeQa(Qa qa) {
		return this.QaMapper.deleteQa(qa);
	}

	@Override
	public int modifyQa(Qa qa) {
		return this.QaMapper.updateQa(qa);
	}

	@Override
	public Map<String, Object> queryQaDetail(Qa qa) {

		List<Map<String, Object>> list = this.QaMapper.selectQa(qa);

		Map<String, Object> map = null;

		if (list != null && list.size() > 0) {
			map = list.get(0);
			String relation = MapUtils.getString(map, "relation");
			String answer = MapUtils.getString(map, "answer");
			if (StringUtils.equals("2", relation)) {
				String[] ids = StringUtils.split(answer, ",");
				Qa childParam = new Qa();
				childParam.setIdsList(Arrays.asList(ids));
				List<Map<String, Object>> childList = this.QaMapper.selectQa(childParam);
				map.put("cqs", childList);
				map.remove("answer");
			}
		}

		return map;
	}

}
